package com.tangtang.rocket.provider;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;

public class RocketMQProducer {
    private static DefaultMQProducer producer;

    static{
        producer = new DefaultMQProducer("my_mq_group");
        producer.setNamesrvAddr("localhost:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        //设置异步发送失败的消息重试次数为0
        producer.setRetryTimesWhenSendAsyncFailed(0);


    }
    //同步
    public  static void send(String topic,String message) throws  Exception{
        Message msg = new Message(topic,
                "tag",
                message.getBytes(StandardCharsets.UTF_8));

        //同步发送消息，代码会卡在这里，只有当mq返回结果，才能继续往下执行代码
        SendResult sendResult = producer.send(msg);
        System.out.println(sendResult);
    }

    //异步
    public   void send1(String topic,String msg) throws  Exception{
        Message message = new Message(topic,
                "tag",
                msg.getBytes(StandardCharsets.UTF_8));

        //异步发送消息
        producer.send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });


    }

    //单向
    public   void send2(Message msg) throws  Exception {
        //发送单向消息
        producer.sendOneway( msg);

    }
}
